package cn.zimo.cityinhand.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

import cn.zimo.cityinhand.R;
import cn.zimo.cityinhand.config.HttpConfig;
import cn.zimo.cityinhand.utils.Isinternet;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author:方少
 * @datetime 2018/7/12
 * @describtion 登陆界面
 *
 */
public class LoginActivity extends Activity {

    private LinearLayout ll_logo;       //logo部分
    private Animation logoMoveIn;        //logo进入动画
    private Animation btnlogin;          //按钮动画
    private EditText et_loginName;      //登陆用户名
    private Button loginButton;         //登录按钮
    private TextView tv_forget;         //忘记密码
    private TextView tv_regist;         //注册账号
    private ImageView img_validate;     //验证码图片
    private LinearLayout ll_validate;   //验证码整体
    private EditText et_validate;       //输入验证码
    private LinearLayout ll_SMS;         //短信密码整体
    private EditText et_SMS;            //输入密码
    final OkHttpClient client = new OkHttpClient();
    static String websiteCode = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        init();
    }

    private void getValidatePic(){
       // GlideApp.with(this).load(HttpConfig.WEB_URL + "/api/auth/getImage?date=" + new Date()).into(img_validate);
        final Request request = new Request.Builder()
                .url(HttpConfig.WEB_URL + "/api/auth/getImage?date=" + new Date())
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final byte[] Picture_bt = response.body().bytes();

                Headers headers = response.headers();
                List cookies = headers.values("Set-Cookie");
                String session = (String)cookies.get(0);
                HttpConfig.SessionId = session.substring(0,session.indexOf(";"));

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(Picture_bt,0,Picture_bt.length);
                        img_validate.setImageBitmap(bitmap);
                    }
                });

            }
        });
    }

    /**
     * 各项初始化
     */
    private void init(){
        //////////////////////////////////加载控件/////////////////////

        ll_logo = findViewById(R.id.logo_title);
        loginButton = findViewById(R.id.btn_login);
        et_loginName = findViewById(R.id.et_loginName);

        // 默认电话号码，懒得输入了
//        et_loginName.setText("15708284990");

        loginButton = findViewById(R.id.btn_login);
        tv_regist = findViewById(R.id.tv_regist);
        tv_forget = findViewById(R.id.tv_forget);
        ll_SMS = findViewById(R.id.ll_SMS);
        ll_validate = findViewById(R.id.ll_validate);
        et_SMS = findViewById(R.id.et_SMS);
        et_validate = findViewById(R.id.et_Validate);
        img_validate = findViewById(R.id.img_Validate);
        getValidatePic();

        //////////////////////////////绑定所有点击事件///////////////////
        loginButton.setOnClickListener(new loginActivityOnClickListener());
        tv_forget.setOnClickListener(new loginActivityOnClickListener());
        tv_regist.setOnClickListener(new loginActivityOnClickListener());
        img_validate.setOnClickListener(new loginActivityOnClickListener());


    }

    class loginActivityOnClickListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btn_login:
                    loginButton.setElevation(10);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            loginButton.setElevation(20);
                        }
                    },200);
                    //TODO:进行登陆操作

                    final String validatecode = et_validate.getText().toString().trim();

////////////////////////////////////验证码验证///////////////////////////////////
                    FormBody vformBody = new FormBody.Builder()
                            .add("code",validatecode)
                            .build();
                    Request vrequest = new Request.Builder()
                            .url(HttpConfig.WEB_URL + "/api/auth/validImage")
                            .post(vformBody)
                            .addHeader("cookie",HttpConfig.SessionId)
                            .build();
                    Call vcall = client.newCall(vrequest);
                   vcall.enqueue(new Callback() {
                       @Override
                       public void onFailure(Call call, IOException e) {

                       }

                       @Override
                       public void onResponse(Call call, Response response) throws IOException {
                           if(response.isSuccessful()){
                               getValidatePic();
                               String  validateresult = response.body().string();
                               if(!validateresult.equals("200")){
                                   runOnUiThread(new Runnable() {
                                       @Override
                                       public void run() {
                                           Toast.makeText(LoginActivity.this,"验证码错误",Toast.LENGTH_SHORT).show();
                                       }
                                   });
                               }else{
///////////////////////////////////////////验证通过，开始登陆/////////////////////////////////////////////////
                                   //登陆
                                   String checkCode = et_SMS.getText().toString().trim();
                                   FormBody LoginformBody = new FormBody.Builder()
                                           .add("checkCode",checkCode)
                                           .add("tel",et_loginName.getText().toString().trim())
                                           .build();
                                   Request Loginrequest = new Request.Builder()
                                           .url(HttpConfig.WEB_URL + "/api/auth/checkCode")
                                           .post(LoginformBody)
                                           .addHeader("cookie",HttpConfig.SessionId)
                                           .build();
                                   Call Logincall = client.newCall(Loginrequest);
                                   Logincall.enqueue(new Callback() {
                                       @Override
                                       public void onFailure(Call call, IOException e) {

                                       }

                                       @Override
                                       public void onResponse(Call call, Response response) throws IOException {
                                           if(response.isSuccessful()){
                                               String json = response.body().string();

                                               try {
                                                   JSONObject jsonObject = new JSONObject(json);
                                                   final String msg = jsonObject.optString("msg");
                                                   final Integer code = jsonObject.optInt("code");
                                                   if (code == 1) {
                                                       JSONObject signjson = jsonObject.optJSONObject("data");
                                                       String sign = signjson.optString("sign");
                                                       HttpConfig.Sign = sign;
                                                       runOnUiThread(new Runnable() {
                                                           @Override
                                                           public void run() {
                                                               Toast.makeText(LoginActivity.this,"登陆成功",Toast.LENGTH_SHORT).show();
                                                           }
                                                       });
                                                       SharedPreferences sharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
                                                       SharedPreferences.Editor editor = sharedPreferences.edit();
                                                       editor.clear();
                                                       editor.commit();
                                                       editor.putString("sessionid",HttpConfig.SessionId);
                                                       editor.putString("sign",HttpConfig.Sign);
                                                       editor.putLong("loginTime",System.currentTimeMillis());
                                                       editor.commit();
                                                       finish();
                                                   }else{
                                                       runOnUiThread(
                                                               new Runnable() {
                                                                   @Override
                                                                   public void run() {
                                                                       Toast.makeText(LoginActivity.this,msg,Toast.LENGTH_SHORT).show();
                                                                   }
                                                               }
                                                       );
                                                       getValidatePic();
                                                   }
                                               }catch (Exception e ){
                                                   e.printStackTrace();
                                               }
                                           }
                                       }
                                   });
                               }
                           }
                       }
                   });




                    /*
                    FormBody LoginformBody = new FormBody.Builder()
                            .add("checkCode",checkCode).build();
                    Request Loginrequest = new Request.Builder()
                            .url(HttpConfig.WEB_URL + "/api/auth/checkCode")
                            .post(LoginformBody)
                            .addHeader("cookie",HttpConfig.SessionId)
                            .build();
                    Call Logincall = client.newCall(Loginrequest);
                    Logincall.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.isSuccessful()){
                                String json = response.body().string();

                                try {
                                    JSONObject jsonObject = new JSONObject(json);
                                    final String msg = jsonObject.optString("msg");
                                    final Integer code = jsonObject.optInt("code");
                                    if(code == 1){
                                        JSONObject signjson = jsonObject.optJSONObject("data");
                                        String sign = signjson.optString("sign");
                                        HttpConfig.Sign = sign;
                                    }
                                    final String sign = jsonObject.optString("sign");
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toasty.normal(LoginActivity.this,msg,Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                        if(code == 1){
                                            SharedPreferences sharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
                                            SharedPreferences.Editor editor = sharedPreferences.edit();
                                            editor.clear();
                                            editor.commit();
                                            editor.putString("sessionid",HttpConfig.SessionId);
                                            editor.putString("sign",HttpConfig.Sign);
                                            Date date = new Date();
                                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                            String Strday = simpleDateFormat.format(date);
                                            editor.putString("day",Strday);
                                            editor.commit();
                                            finish();
                                        }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                        }
                    });*/
                    break;
                case R.id.tv_forget:
                    //TODO：忘记密码操作
                    break;
                case R.id.tv_regist:
                    //TODO：注册页面
                    break;
                case R.id.img_Validate:
                    //点击验证码刷新验证码
                    //GlideApp.with(LoginActivity.this).load(HttpConfig.WEB_URL + "/api/auth/getImage?date=" + new Date()).into(img_validate);
                    getValidatePic();
                    break;
               /* case R.id.btn_SMSButton: {
                    final String validate = et_validate.getText().toString().trim();
                    final String Tel = et_loginName.getText().toString().trim();
                    if (!isPhoneAvailable(Tel)) {
                        Toasty.normal(LoginActivity.this, "手机号码不符合规则", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (validate.equals("") || validate == null) {
                        Toasty.normal(LoginActivity.this, "验证码不可为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //验证码确认
                    FormBody formBody = new FormBody.Builder().add("code", validate).build();

                    final Request request = new Request.Builder()
                            .url(HttpConfig.WEB_URL + "/api/auth/validImage")
                            .addHeader("cookie", HttpConfig.SessionId)
                            .post(formBody).build();
                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Toasty.error(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            final String cod = response.body().string();
                            if (response.isSuccessful()) {
                                runOnUiThread(new Runnable() {
                                    //TimerRunner tr = null;
                                    @Override
                                    public void run() {
                                        //先修改验证码
                                        if (!cod.equals("200")) {
                                            Toasty.normal(LoginActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                                            getValidatePic();
                                        } else {
                                            /////////验证过后发送短信////////////
                                            Toasty.normal(LoginActivity.this, "短信发送中...", Toast.LENGTH_SHORT).show();
                                            btn_SMS.setEnabled(false);
                                            //tr = new TimerRunner();
                                            FormBody formBody = new FormBody.Builder().add("tel", Tel).build();
                                            Request request = new Request.Builder()
                                                    .url(HttpConfig.WEB_URL + "/api/auth/send")
                                                    .addHeader("cookie", HttpConfig.SessionId)
                                                    .post(formBody)
                                                    .build();
                                            Call call2 = client.newCall(request);
                                            call2.enqueue(new Callback() {
                                                @Override
                                                public void onFailure(Call call, IOException e) {

                                                }

                                                @Override
                                                public void onResponse(Call call, Response response) throws IOException {
                                                    final String result = response.body().string();
                                                    if (response.isSuccessful()) {
                                                        // tr.stoptim();
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                btn_SMS.setEnabled(true);
                                                                Toasty.normal(LoginActivity.this, result, Toast.LENGTH_SHORT).show();
                                                                // 自动填充密码
//                                                                et_SMS.setText(result.substring(result.indexOf("：" + 1)));
                                                            }
                                                        });
                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        }
                    });

                    break;
                }*/
            }
        }

        //验证手机号是否正确
        private boolean isPhoneAvailable(String str){
            String myreg = "^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\\d{8})$";
            return Pattern.matches(myreg,str);
        }


    }

    static class Gist {
        Map<String, GistFile> files;
    }

    static class GistFile {
        String content;
    }

}

